﻿using System;
using System.ComponentModel;
using System.Reflection;

namespace BLL.Extensions
{
    /// <summary>
    /// Extension methods for <see cref="Enum"/>.
    /// </summary>
    public static class EnumExtensions
    {
        /// <summary>
        /// Gets the description attribute value for the specified enumeration value.
        /// </summary>
        /// <param name="value">The value to get description for.</param>
        /// <returns>
        /// Returns string representation of value if <see cref="DescriptionAttribute"/> doesn't specified.
        /// </returns>
        public static string GetDescription(this Enum value)
        {
            try
            {
                Type type = value.GetType();
                string name = Enum.GetName(type, value);

                FieldInfo field = type.GetField(name);
                if (field != null)
                {
                    var attr = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute));
                    if (attr != null)
                        return ((DescriptionAttribute)attr).Description;
                }

                return Convert.ToString(value);
            }
            catch (NullReferenceException)
            {
                return null;
            }
            catch (ArgumentException)
            {
                return null;
            }
        }
    }
}